<template>
  <div>
    <el-row :gutter="6" style="padding: 10px">
      <el-col :span="10" style="margin-left: 10px">
        <el-card class="box-card">
          <template #header>
            <div class="card-header justify-between">
              <div class="text">用户列表</div>
              <div>
                <el-input
                  v-model="userQuery.userName"
                  placeholder="请输入用户名称"
                  clearable
                  size="small"
                  @keyup.enter="handleUserFilter"
                  width="100"
                />
                <el-button
                  type="primary"
                  size="small"
                  icon="Search"
                  @click="handleUserFilter"
                >
                  筛选
                </el-button>
              </div>
            </div>
          </template>
          <el-table
            row-class-name="table-row-selectable"
            v-loading="userLoading"
            highlight-current-row
            :data="userList"
            style="height: 59vh; width: 32vw"
            @row-click="handleUserClick"
          >
          <el-table-column prop="userName" label="用户名" />
            <el-table-column prop="phoneNumber" label="手机号" />
            <el-table-column prop="organizationName" label="部门" />
          </el-table>
          <!-- 分页组件 -->
          <pagination
            small
            v-show="userTotal > 0"
            :total="userTotal"
            v-model:page="userQuery.pageNum"
            v-model:limit="userQuery.pageSize"
            :layout="'prev, pager, next'"
            @pagination="getUserList"
          />
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="box-card">
          <template #header>
            <div class="card-header justify-between">
              <div class="text">角色列表</div>
              <div>
                <el-input
                  size="small"
                  v-model="roleQuery.name"
                  placeholder="请输入角色名称"
                  clearable
                  @keyup.enter="handleRoleFilter"
                  width="100"
                />
                <el-button
                  size="small"
                  type="primary"
                  icon="Search"
                  @click="handleRoleFilter"
                >
                  筛选
                </el-button>
                <span
                    v-hasPermi="['system:userRole:add']"
                    class="ml-2"
                >
                  <el-button
                      type="primary"
                      icon="Check"
                      @click="saveUserRoles"
                      size="small"
                  >
                    保存
                  </el-button>
                  <el-button icon="Refresh" @click="handleReset" size="small"
                  >重置
                  </el-button>
                </span>
              </div>
            </div>
          </template>
          <el-table
            v-loading="isLoading"
            :data="roleList"
            style="height: 59vh"
            @select="handleSelectionChange"
            @select-all="handleSelectAll"
            ref="roleTable"
          >
            <el-table-column
              type="selection"
              width="30"
              align="center"
              :show-select-all="false"
            />
            <el-table-column prop="name" label="角色名" />
            <!-- <el-table-column prop="key" label="角色key" /> -->
            <el-table-column label="状态" prop="status">
              <template #default="{ row }">
                <el-tag :type="statusType(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  v-show="scope.row.isChecked"
                  link
                  type="primary"
                  @click="handleSetting(scope.row)"
                  >管理范围</el-button
                >
              </template>
            </el-table-column> -->
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import {
  getUserList as getUserListApi,
  getRoleList as getRoleListApi,
  saveUserRoles as saveUsersApi,
} from "@/service/api/system/userRole";
import to from "await-to-js";
import Pagination from "@/components/Pagination/index.vue";
import {
  SysRoleVo,
  SysUserInfoVo,
  SysUserVo,
} from "@/service/api/system/userRole/types.ts";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";

const userLoading = ref(false);
const roleLoading = ref(false);
const isLoading = ref(false);
const roleTable = ref();
const initDialogData = {
  title: "",
  isVisible: false,
};

const initQueryParams = {
  userId: "",
  roleId: "",
};

declare type SysRoleVoWithExtra = SysRoleVo & {
  roleId?: string;
  isChecked?: boolean;
};

const data = reactive({
  roleList: <SysRoleVoWithExtra[]>[],
  userList: <SysUserVo[]>[],
  // 获取用户BO
  userQuery: {
    userName: "",
    pageSize: 10,
    pageNum: 1,
    orderByColumn: "createTime",
    orderType: "desc",
  },
  // 获取角色BO
  roleQuery: {
    name: "",
    orderByColumn: "createTime",
    orderType: "desc",
  },
  dialogData: {
    ...initDialogData,
  },
  // 用户绑定角色时的参数
  queryParams: {
    ...initQueryParams,
  },
  checkedRoleIdList: <string[]>[],
});
const {
  userList,
  roleList,
  userQuery,
  roleQuery,
  queryParams,
  checkedRoleIdList,
} = toRefs(data);

const userTotal = ref(0);

/**
 * 获取用户列表
 */
const getUserList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<SysUserVo>, any>(
    getUserListApi(userQuery.value),
  );

  if (!err) {
    userList.value = res?.rows ?? [];
    userTotal.value = Number(res?.total ?? 0);
    return true;
  }
  return false;
};

/**
 * 获取角色列表以及给用户勾选的角色
 * @param userId
 */
const getRoleList = async (userId: string): Promise<boolean> => {
  const [err, res] = await to<BaseResponse<SysUserInfoVo>, any>(
    getRoleListApi(userId, roleQuery.value),
  );

  if (!err) {
    roleList.value = res?.data?.roles ?? [];
    roleList.value.forEach((item: SysRoleVoWithExtra) => {
      // 为每个节点加一个roleId防止报错
      item.roleId = item.id;
      if (item.status === "1") {
        item.status = "停用";
      } else if (item.status === "2") {
        item.status = "禁言";
      } else if (item.status === "3") {
        item.status = "未确认";
      } else {
        item.status = "正常";
      }
    });
    checkedRoleIdList.value = res?.data?.roleIds ?? [];
    console.log(checkedRoleIdList.value);

    // 默认勾选
    nextTick(() => {
      checkedRoleIdList.value.forEach((key: string) => {
        const row = roleList.value.find(
          (item: SysRoleVoWithExtra) => item.id === key,
        );
        if (row) {
          // 新增isChecked用于展示管理按钮
          row.isChecked = true;
          roleTable.value.toggleRowSelection(row, true);
        }
      });
    });
    console.log(roleList.value);

    return true;
  }
  return false;
};

// 设置状态
const statusType = (status: string) => {
  switch (status) {
    case "正常":
      return "success";
    case "未确认":
      return "warning";
    case "禁言":
      return "danger";
    case "停用":
      return "info";
    default:
      return "";
  }
};

// 当前角色id
const currentUserId = ref();
// 当前勾选列表
const currentCheckedList = ref<SysRoleVoWithExtra[]>([]);
const currentRoleItem = ref({
  roleId: "",
  regionDataScope: {
    allow: [],
    deny: [],
  },
  organizationDataScope: {
    allow: [],
    deny: [],
  },
});

/**
 * 处理用户列表被点击
 * @param row
 */
const handleUserClick = async (row: any) => {
  roleLoading.value = true;
  // 获取当前用户id
  queryParams.value.userId = row.id;
  currentUserId.value = row.id;
  await getRoleList(row.id);
  roleLoading.value = false;
};

/**
 * 处理角色列表勾选
 * @param selection
 * @param row
 */
const handleSelectionChange = async (
  selection: SysRoleVoWithExtra[],
  row: SysRoleVoWithExtra,
) => {
  // 记录当前勾选
  currentRoleItem.value.roleId = row.id;
  // 防止没有roleId字段报错
  row.roleId = row.id;
  // 数据和界面一致
  row.isChecked = !row.isChecked;
  console.log(selection, row);
  console.log(roleList.value);
};

/**
 * 保存绑定按钮
 */
const saveUserRoles = async () => {
  // 筛选列表中勾选的
  isLoading.value = true;
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定要保存所有角色?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消保存",
    });
  } else if (confirm === "confirm") {
    // 获取所有已勾选的角色列表
    currentCheckedList.value = roleList.value.filter(
      (item: SysRoleVoWithExtra) => item.isChecked === true,
    );

    console.log(currentCheckedList.value);
    isLoading.value = true;
    const [err] = await to<BaseResponse<any>, any>(
      saveUsersApi(currentUserId.value, currentCheckedList.value),
    );
    if (!err) {
      ElMessage({
        type: "success",
        message: "保存成功",
      });
    }
  }
  isLoading.value = false;
};

/**
 * 处理重置按钮
 */
const handleReset = async () => {
  const [err] = await to<string, string>(
    ElMessageBox.confirm("是否重置所有勾选，回到初始状态?", "提示", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消重置，勾选依然是未保存状态",
    });
  } else {
    ElMessage({
      type: "success",
      message: "重置成功，恢复到加载时状态",
    });
    await getRoleList(currentUserId.value);
  }
};

/**
 * 全选按钮
 * @param selection
 */
const handleSelectAll = async (selection: SysRoleVoWithExtra[]) => {
  checkedRoleIdList.value = [];
  currentCheckedList.value = selection;

  if (currentCheckedList.value && currentCheckedList.value.length > 0) {
    nextTick(() => {
      currentCheckedList.value.forEach((key: SysRoleVoWithExtra) => {
        const row = roleList.value.find(
          (item: SysRoleVoWithExtra) => item.id === key.roleId,
        );
        if (row) {
          // 新增isChecked用于展示管理按钮
          row.isChecked = true;
          roleTable.value.toggleRowSelection(row, true);
        }
      });
    });
  } else {
    roleList.value.map((item: any) => {
      item.isChecked = false;
    });
  }
  console.log(roleList.value);
};

/**
 * 处理过滤用户
 */
const handleUserFilter = () => {
  getUserList();
};

/**
 * 处理过滤角色
 */
const handleRoleFilter = () => {
  getRoleList(currentUserId.value);
};

onMounted(() => {
  getUserList();
});
</script>

<style scoped>
.card-header {
  display: flex;

  .text {
    width: 150px;
    /* background-color: aqua; */
  }

  .el-input {
    margin: 0 5px 0 0;
    width: 200px;
  }
}

.dialogFooter {
  margin: 20px 0 0 170px;
}
</style>
